package emulator.shell.GUI.menu;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import emulator.hardware.clock.Clock;
import emulator.hardware.clock.ClockImpl2;
import emulator.shell.GUI.windows.ManagedWindow;
import emulator.shell.GUI.windows.WindowManager;

public class WindowSettings implements ActionListener
{
	private int _windowId;
	private WindowManager _windowManager;
	private ClockImpl2 _clock;

	public WindowSettings(WindowManager windowManager, int windowId, Clock clock)
	{
		_windowManager = windowManager;
		_windowId = windowId;
		_clock = (ClockImpl2)clock;
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		if (_windowManager.isWindowActive(_windowId))
			closeWindow();
		else
			openWindow();
	}

	private void openWindow() 
	{
		ManagedWindow window = _windowManager.createWindow(_windowId, "Settings");
		initDialog(window);
		window.restorePosition();
		window.setVisible(true);
	}

	private void closeWindow()
	{
		_windowManager.closeWindow(_windowId);
	}

	private void initDialog(ManagedWindow window)
	{
		JLabel title = new JLabel("Clock emulation", JLabel.CENTER);
		title.setFont(new Font("Arial", Font.BOLD, 16));
		JLabel leftText = new JLabel("Accuracy");
		JLabel rightText = new JLabel("Speed");
		JSlider sliderThreshhold = new JSlider(JSlider.HORIZONTAL, 0, 10, _clock.getSyncThreshhold());
		sliderThreshhold.setMajorTickSpacing(5);
		sliderThreshhold.setMinorTickSpacing(1);
		sliderThreshhold.setPaintTicks(true);
		sliderThreshhold.addChangeListener(new ThreshholdChangeListener());
		
		Container panel = window.getContentPane();
		panel.setLayout(new BorderLayout());
		panel.add(title, BorderLayout.NORTH);
		panel.add(leftText, BorderLayout.WEST);
		panel.add(rightText, BorderLayout.EAST);
		panel.add(sliderThreshhold, BorderLayout.CENTER);
	}

	public class ThreshholdChangeListener implements ChangeListener
	{
		@Override
		public void stateChanged(ChangeEvent e)
		{
			JSlider source = (JSlider)e.getSource();
		    if (!source.getValueIsAdjusting())
		    {
		        int threshhold = (int)source.getValue();
		        if (threshhold < 1)
		        	threshhold = 1;
		        _clock.setSyncThreshhold(threshhold);
		    }
		}
	}
}
